// Category and author pages have different preview tag classes:
var thumbnailSelector = ".photolist a.preview170 img, .photolist a.preview230 img";

var slidesPerPage = 0;
var img_tags = "<div id='slides'>";
$(thumbnailSelector).each(function(index, element) {
  img_tags += createImageTag(this);
  ++slidesPerPage;
})
img_tags += "</div>";

var slideStack = [];
var currentSlideNo = 1;

// Tracks the URL of the next page to load.
var nextPage = {
  url: "",
  number: 2
};

// Store the URL to use for fetching the next page.
$("a.g-paginator-next").each(function(index, element) {
  nextPage.url = $(this).attr("href");
  nextPage.number = parseInt(nextPage.url.match(/pager=([^&]+)/)[1]);
  console.log("Next page url: " + nextPage.url);
});

// Create the slide div
$(img_tags).appendTo("body");
setStyles()

// Bind keyboard shortcuts:
// j: next slide
// k: previous slide
$(document).bind('keypress', function(e) {
  console.log("key: " + e.keyCode);
  if (e.keyCode == 106) { // j
    $('#slides').cycle('next');
  } else if (e.keyCode == 107) {// k
    $('#slides').cycle('prev');
    currentSlideNo -= 2;
  }
});

// Start the slide show.
$('#slides').cycle({
  fx: 'fade',
  speed:  300, 
  next:   '#slides', 
  timeout: 0,
  nowrap: true,
  before:  onBeforeSlide
});

function setStyles() {
  $("#slides").css({
     position: "fixed",
     top: 0,
     left: 0,
     width: "100%",  
     height: "100%",  
     background: "#000",
     background: "#000",
     "z-index": 999 
  });
  $("#slides div").css({
     width: "100%",  
     height: "100%"  
  });
  $("#slides div img").css({
    "max-width": "90%",
    "max-height": "90%",
    margin: "40px auto 60px",
    display: "block"
  });
}

function onBeforeSlide(curr, next, opts) {
  currentSlideNo++;

  if (opts.addSlide) {
    console.log("Stack " + slideStack.length + ", Current=" + currentSlideNo);
    while (slideStack.length) {
      var img = slideStack.pop();
      console.log("adding slide: " + img);
      opts.addSlide(img);
    }
    setStyles()
  }
  if ((currentSlideNo + 5) % slidesPerPage == 0) {
    console.log("Loading next page");
    loadNextPage();
  }
}

function loadNextPage() {
  console.log("Fetching page: " + nextPage.url);
  $.get(nextPage.url, function(data) {
    console.log("Next page ready:");
    slidesPerPage = 0;
    $(data).find(thumbnailSelector).each(function(index, element) {
      slideStack.push(createImageTag(this));
      ++slidesPerPage;
    });
    nextPage.number++;
    nextPage.url = nextPage.url.replace(/pager=.*/, "pager=" + nextPage.number);
  });
}

function createImageTag(thumb_img) {
  return "<div><img src='"
    + $(thumb_img).attr("src").replace("_thumb", "_large")
    + "'></div>";
}

